<route>
    {
        meta: {
            layout: 'index',
            title:'打捞施工指导'
        }
    }  
</route>
<template>
  <div>
    <div>
      <!-- 功能选择 -->
      <a-row v-if="selectAccident == false && selectCard == false">
        <a-col :span="3">
          <a-button type="dashed" style="width: 100%" @click="openAddWell">新建指导方案</a-button>
        </a-col>
        <a-col :span="3" style="margin-left: 10px">
          <a-button type="dashed" style="width: 100%" @click="openList">选择指导方案</a-button>
        </a-col>
        <!-- <a-col :span="3" style="margin-left:10px; ">
        <a-button type="dashed" style="width: 100%" @click="openAddWell">上传井眼轨迹</a-button>
      </a-col> -->
        <a-col :span="3" style="margin-left: 10px">
          <a-button type="dashed" style="width: 100%" @click="openWord('穿心解卡施工方案')">施工方案报告</a-button>
        </a-col>
      </a-row>
      <a-row v-if="selectAccident != false || selectCard != false">
        <a-button type="primary" style="margin-left: auto; margin-bottom: 10px; margin-right: 10px; width: 100px"
          @click="returned()">返回</a-button>
      </a-row>
      <!-- 施工方案信息 -->
      <div v-if="selectAccident == false && selectCard == false">
        <a-row :gutter="20" style="margin-top: 10px">
          <!-- 左侧折叠面板 -->
          <a-col :span="12">
            <BasicData v-if="isDataReady" :solutionDetail="solutionDetail"></BasicData>
            <a-collapse v-model:activeKey="activeKey" :bordered="false">
              <!-- <a-collapse-panel key="基础信息" header="基础信息" :collapsible="collapse">
                <solution-data :solutionDetail="solutionDetail"></solution-data>
              </a-collapse-panel>
              <a-collapse-panel key="打捞筒推荐" header="打捞筒推荐" :collapsible="collapse">
                <Tube :salvageTube="solutionDetail.salvageTube"></Tube>
              </a-collapse-panel> -->
              <a-collapse-panel key="地面工具推荐" header="地面工具推荐" :collapsible="collapse">
                <template #extra>
                  <a-button type="link" size="small" @click="openWord('工具选配表')">文档生成</a-button>
                </template>
                <GroundTools :groundToolList="solutionDetail.groundToolList"></GroundTools>
              </a-collapse-panel>
              <!-- <a-collapse-panel key="卡瓦选择提示" header="卡瓦选择提示" :collapsible="collapse">
                <KavaSelect></KavaSelect>
              </a-collapse-panel> -->
              <a-collapse-panel key="风险提示" header="风险提示" :collapsible="collapse">
                <RiskWarning :solutionDetail="solutionDetail"></RiskWarning>
              </a-collapse-panel>
            </a-collapse>
          </a-col>

          <!-- 右侧绘图 -->
          <a-col :span="12">
            <a-card>
              <a-tabs v-model:activeKey="drawActiveKey">
                <a-tab-pane key="井眼轨迹图">
                  <template #tab><span>井眼轨迹图</span></template>
                  <div ref="chartContainer">
                    <EchartCanvas ref="lithologyRef" :echartsData="solutionDetail"></EchartCanvas>
                  </div>
                </a-tab-pane>
                <a-tab-pane key="打捞示意图">
                  <template #tab><span>打捞示意图</span></template>
                  <salvageCanvas></salvageCanvas>
                </a-tab-pane>
                <a-tab-pane key="打捞工具组装视频">
                  <template #tab><span>打捞工具组装视频</span></template>
                  <player></player>
                </a-tab-pane>
                <a-tab-pane key="模拟打捞动画">
                  <template #tab><span>模拟打捞动画</span></template>
                  <player></player>
                </a-tab-pane>
                <a-tab-pane key="主要危险源辨识">
                  <template #tab><span>主要危险源辨识</span></template>
                  <div style="height: 550px; overflow: auto">
                    <major-hazards></major-hazards>
                  </div>
                </a-tab-pane>
              </a-tabs>
            </a-card>
          </a-col>
        </a-row>

        <!-- 新增施工方案弹窗 -->
        <AntdConfirmModal title="生成施工方案" ref="wellModalRef" width="800px" @confirm="submitInfo">
          <a-form :model="params" name="basic" :label-col="{ span: 8 }">
            <a-row>
              <a-col :pull="3" :span="22">
                <a-form-item label="选择已有井" name="wellId">
                  <!-- <well-select style="width: 400px" @confirm="getSelectWell"></well-select> -->
                  <AccidentWell style="margin-right: 16px; width: 180px;" @confirm="getSelectWell">选择已有井
                  </AccidentWell>
                </a-form-item>
              </a-col>
              <a-col :pull="3" :span="22">
                <a-form-item label="卡点测深" name="stuckPointsDeep">
                  <a-input-number style="width: 400px" v-model:value="stuckPointsDeep" :min="0" />
                </a-form-item>
              </a-col>
              <a-col :pull="3" :span="22">
                <a-form-item label="仪器顶部深度" name="instrumentTopPosition">
                  <a-input-number style="width: 400px" v-model:value="instrumentTopPosition" :min="0" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :pull="3" :span="22">
                <a-form-item label="上传附件">
                  <a-upload-dragger withCredentials v-model:fileList="fileList" style="width: 450px" name="file"
                    :before-upload="beforeUpload" @remove="handleRemove" :maxCount="1">
                    <p class="ant-upload-drag-icon">
                      <inbox-outlined></inbox-outlined>
                    </p>
                    <p class="ant-upload-text">点击或者拖拽文件到此处上传</p>
                  </a-upload-dragger>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <a-table :dataSource="schemeArray" :columns="wellSelectColumns" bordered :pagination="false"
            style="margin-left: 15px; margin-right: 40px">
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'action'">
                <div style="margin-right: 8px">
                  <span>
                    <a-button type="link" @click="openDetail(record)">查看详细信息</a-button>
                  </span>
                </div>
              </template>
            </template>
          </a-table>
        </AntdConfirmModal>

        <!-- 施工方案列表弹窗 -->
        <AntdConfirmModal title="施工方案列表" ref="listModalRef" width="800px">
          <solution-popup @solutionSelection="solutionSelection"></solution-popup>
        </AntdConfirmModal>
      </div>

      <!-- 事故快报详细信息 -->
      <view v-if="selectAccident">
        <AccidentDetail :reportId="selectAccident"></AccidentDetail>
      </view>
      <!-- 收集卡详细信息 -->
      <view v-if="selectCard">
        <card-unlock-detail :reportId="selectCard"></card-unlock-detail>
      </view>
    </div>
    <!-- 详细信息抽屉 -->
    <a-drawer width="65%" title="在线预览" v-model:visible="open">
      <template #extra>
        <a-button type="primary" @click="exReport">下载</a-button>
      </template>
      <FileList :fileIds="fileIds"></FileList>
    </a-drawer>
  </div>
</template>
<script setup>
import { InboxOutlined } from "@ant-design/icons-vue";
import BasicData from "./data/BasicData.vue";
import SalvageSchemes from "@/api/salvage/planDesign.js";
import AccidentApi from '@/api/salvage/accidentAlert.js'
import ThreadCardApi from "@/api/salvage/threadCard.js";
import WellCable from "@/api/tool/cable.js";
import WellCombination from "@/api/tool/combination.js";
import WellAnalysis from '@/api/v3/mechanical.js'
import { exportList } from "@/api/design/export.js";
import AccidentWell from '@/custom/salvage/components/AccidentWell'
import FileList from "@/custom/salvage/components/FileList.vue";
import MajorHazards from "@/custom/salvage/pages/engineering/training/majorHazards";
// import EchartCanvas from "@/custom/preTest/pages/plan/components/data/echarts";
import EchartCanvas from "./draw/trajectory/echarts.vue";
import salvageCanvas from "./draw/salvage/index.vue";
import player from "./draw/video/player.vue";
import WellSelect from "@/custom/well/components/WellSelect";
import WellSurvey from "@/api/survey/survey.js";
import SolutionPopup from "@/custom/salvage/components/SolutionPopup";
import KavaSelect from "./data/KavaSelect.vue";
import RiskWarning from "./data/RiskWarning.vue";
import AccidentDetail from "@/custom/salvage/pages/engineering/accidentReport/detail";
import CardUnlockDetail from "@/custom/salvage/pages/engineering/cardUnlocking/detail";
import GroundTools from "./data/GroundTools.vue";
import Tube from "./data/Tube.vue";
import SolutionData from "@/custom/salvage/pages/engineering/salvageGuidance/data/SolutionData";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import "moment/locale/zh-cn";
import moment from "moment";
import request from "@/utils/request";
import useApp from "@/hooks";
const { $, proxy } = useApp();
const fileList = ref([]);
const file = ref();
const form = ref({
  file: null,
  bucketName: "importPre",
  remark: "",
});
const open = ref(false);
const lithologyRef = ref(null);
const drawActiveKey = ref("井眼轨迹图"); //绘图标签切换
const activeKey = ref(''); //折叠面板切换
const wellModalRef = ref(null); //新增弹窗
const schemeArray = ref([]); //所选井含有的信息卡
const accidentData = ref(); //所选井的快报信息
const cardUnlockData = ref(); //所选井的收集卡信息
const selectedReport = ref(false); //方案id
const selectAccident = ref(false); //快报id
const selectCard = ref(false); //收集卡id
const solutionDetail = ref(); //方案信息
const listModalRef = ref(null); //方案列表弹窗
const collapse = ref("header"); //控制折叠面板是否可触发
const stuckPointsDeep = ref(0); //卡点深度
const instrumentTopPosition = ref(0); //仪器顶部深度
const allPlan = ref([]); // 存储所有方案
const doSchemeData = ref();
const combSuggesQuery = ref({}); //仪器串相关信息
const isDataReady = ref(false)  //确认数据已经准备好了
const querySurvey = ref({ order: "DESC", pageNum: 1, pageSize: 10, sortBy: "id", wellId: "" });
// 弹窗表格配置
const fileIds = ref({
  id: "",
  type: "",
});
const wellSelectColumns = [
  {
    title: "信息表",
    dataIndex: "title",
    key: "title",
    width: "50%",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
  },
];
// 文件上传
const beforeUpload = (file) => {
  console.log("beforeUpload", file);
  // 记录文件
  form.value.file = file;
  if (
    file.type !== "application/vnd.ms-excel" &&
    file.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  ) {
    $.showToast({
      title: "只支持上传excel文件",
      icon: "error",
    });
    return false;
  }
  return true;
  // 直接停止上传
  // return false;
};
// 移除文件
const handleRemove = (file) => {
  form.value.file = null;
};

// 打开新增方案窗口
function openAddWell() {
  wellModalRef.value.openModal();
}

// 获得已存在的快报/收集卡
// function getSelectWell(e) {
//   console.log('e', e);
//   schemeArray.value = [];
//   querySurvey.value.wellId = e
//   console.log(querySurvey.value);
//   Promise.all([
//     AccidentApi.queryLastList(querySurvey.value),
//     ThreadCardApi.queryLastList(querySurvey.value)
//   ]).then((res) => {
//     console.log("res", res);
//     if (res[0].content.length == 0) {
//       $.showToast({
//         title: "无工程事故复杂快报信息",
//         icon: "warn",
//       });
//     } else {
//       accidentData.value = res[0].content[0];
//       accidentData.value.title = `${e}井的事故快报信息卡`;
//       schemeArray.value.push(accidentData.value);
//     }
//     if (res[1].content.length == 0) {
//       $.showToast({
//         title: "无穿心解卡现场信息",
//         icon: "warn",
//       });
//     } else {
//       cardUnlockData.value = res[1].content[0];
//       cardUnlockData.value.title = `${e}井的穿心解卡信息收集卡`;
//       schemeArray.value.push(cardUnlockData.value);
//     }
//     console.log("schemeArray.value", schemeArray.value);
//   });
// }
function getSelectWell(wellId) {
  console.log('wellId', wellId);
  schemeArray.value = [];
  querySurvey.value.wellId = wellId
  Promise.all([
    AccidentApi.queryLastList(querySurvey.value),
    ThreadCardApi.queryLastList(querySurvey.value)
  ]).then((res) => {
    console.log("res", res);
    accidentData.value = res[0].content[0];
    accidentData.value.title = `${wellId}井的事故快报信息卡`;
    schemeArray.value.push(accidentData.value);
    if (res[1].content.length == 0) {
      $.showToast({
        title: "无穿心解卡现场信息",
        icon: "warn",
      });
    } else {
      cardUnlockData.value = res[1].content[0];
      cardUnlockData.value.title = `${wellId}井的穿心解卡信息收集卡`;
      schemeArray.value.push(cardUnlockData.value);
    }
    console.log("schemeArray.value", schemeArray.value);
  });
}

// 打开详细面板
function openDetail(e) {
  console.log("openDetail", e);
  if (e.title.includes("事故快报信息卡")) {
    selectAccident.value = e.id;
    console.log("selectedReport.value", selectedReport.value);
  } else if (e.title.includes("穿心解卡信息收集卡")) {
    selectCard.value = e.id;
  }
}
// 获取电缆信息
function getCableDate(id) {
  WellCable.queryOne(id).then((res) => {
    if (res.createdTime) {
      res.createdTime = dayjs(res.createdTime).format("YYYY-MM-DD HH:mm:ss");
    }
    if (res.updatedTime) {
      res.updatedTime = dayjs(res.updatedTime).format("YYYY-MM-DD HH:mm:ss");
    }
    doSchemeData.value.cable = res;
    // console.log(doSchemeData.value.cable);
  });
}
//打开Word预览
function openWord(type) {
  //浅拷贝解决重新渲染问题
  fileIds.value.type = type;
  fileIds.value.id = localStorage.getItem("solutionId");
  fileIds.value = JSON.parse(JSON.stringify(fileIds.value));
  open.value = true;
}
// 查询仪器串信息
function getcombSuggest(id) {
  //查询仪器串包含的仪器所有信息
  WellCombination.getOne(id).then((res) => {
    // console.log(res);
    // combSuggesQuery.value.instrumentIdList = [];
    combSuggesQuery.value.totalLength = 0;
    combSuggesQuery.value.maxOuterDiameter = 0;
    combSuggesQuery.value.totalWeight = 0;
    // 查找是否含有马笼头
    res.forEach((e) => {
      // 如果有，将马笼头仪器参数名称与其他仪器参数名称统一
      if (e.hasOwnProperty("horseheadId")) {
        e.instrumentId = e.horseheadId;
        e.outerDiameter = e.maxDiameter;
        e.instrumentName = e.horseheadName;
        e.weight = 0;
      }
      //为新建仪器串推荐负载参数赋值
      combSuggesQuery.value.maxOuterDiameter =
        combSuggesQuery.value.maxOuterDiameter > e.outerDiameter
          ? combSuggesQuery.value.maxOuterDiameter
          : e.outerDiameter;
      combSuggesQuery.value.totalLength = combSuggesQuery.value.totalLength + e.length;
      combSuggesQuery.value.totalWeight = combSuggesQuery.value.totalWeight + e.weight;
      // combSuggesQuery.value.instrumentIdList.push(e.id);
    });
    // combSuggesQuery.value.instrumentCombination = item.instrumentNameList;
    combSuggesQuery.value.totalWeight = combSuggesQuery.value.totalWeight.toFixed(2);
    combSuggesQuery.value.totalLength = combSuggesQuery.value.totalLength.toFixed(2);
    // combSuggesQuery.value.schemeId = localStorage.getItem("schemeId");
    doSchemeData.value.instrumentBottomDepth =
      instrumentTopPosition.value + parseFloat(combSuggesQuery.value.totalLength);
  });
  // console.log('combSuggesQuery', combSuggesQuery.value);
}
// 新增方案窗口的提交(合成施工方案)
function submitInfo() {
  if (schemeArray.value.length !== 2) {
    $.showToast({
      title: "缺少关键信息表无法生成施工方案",
      icon: "warn",
    });
  } else if (accidentData.value.combinationId != cardUnlockData.value.combinationId) {
    $.showToast({
      title: "快报和收集卡中的仪器串信息不同，无法生成施工方案",
      icon: "warn",
    });
  } else if (accidentData.value.cableId != cardUnlockData.value.cableId) {
    $.showToast({
      title: "快报和收集卡中的电缆信息不同，无法生成施工方案",
      icon: "warn",
    });
  } else {
    doSchemeData.value = { ...accidentData.value, ...cardUnlockData.value };
    if (form.value.file == null) {
      $.showToast({
        title: "请上传井眼轨迹",
        icon: "warn",
      });
    } else {
      getCableDate(doSchemeData.value.cableId);
      getcombSuggest(doSchemeData.value.combinationId);
      doSchemeData.value.stuckPointsDeep = stuckPointsDeep.value;
      doSchemeData.value.instrumentTopPosition = instrumentTopPosition.value;
      console.log("doSchemeData", doSchemeData.value);
      // 检查该井的施工方案是否存在
      const isValueInArray = allPlan.value.some((obj) => obj.wellId === doSchemeData.value.wellId);
      console.log('施工方案是否存在', isValueInArray);
      if (isValueInArray) {
        $.showToast({
          title: "该井的施工方案已存在",
          icon: "warn",
        });
      } else {
        SalvageSchemes.createSchemes(doSchemeData.value.wellId).then((response) => {
          console.log("createSchemes", response);
          localStorage.setItem("solutionId", response.id); //存储解决方案ID
          localStorage.setItem("salvageWellId", response.wellId);
          // 删除测井记录
          WellAnalysis.delSurvey(doSchemeData.value.wellId).then((sur) => {
            console.log("当前井测井记录已清空");
            // 上传井眼轨迹
            const formData = new FormData();
            if (doSchemeData.value.wellType == '直井') {
              formData.append("remark", doSchemeData.value.wellType);
            } else {
              formData.append("remark", '定向井');
            }
            formData.append("file", form.value.file);
            formData.append("wellId", doSchemeData.value.wellId);
            // console.log('上传井眼轨迹时formData', Array.from(formData.entries()));
            request.post("/well/survey/import", formData, {
              headers: {
                "Content-Type": "multipart/form-data",
              },
            }).then((res) => {
              console.log("井眼轨迹", res);
              localStorage.setItem("salvageFileId", res.id);
              $.showToast({
                title: "井眼轨迹上传成功",
                icon: "success",
              });
              localStorage.setItem("isSalPoint", res.skew)
              WellAnalysis.interWell(doSchemeData.value.wellId, 1, res.skew).then((inter) => {
                // 插值
                console.log("插值", inter);
                // 卡点位置匹配
                inter.content.forEach((ele) => {
                  if (ele.depth == doSchemeData.value.stuckPointsDeep) {
                    doSchemeData.value.pointWellLocation = ele.azimuth.toFixed(2); //方位
                    doSchemeData.value.pointWellSlope = ele.inclination.toFixed(2); //井斜
                    doSchemeData.value.stuckPointsDoglegDegree = ele.dog_leg_severity.toFixed(2); //狗腿度
                  }
                });

                SalvageSchemes.updateOne(response.id, doSchemeData.value).then((e) => {
                  console.log("updateOne", e);
                  $.showToast({
                    title: "方案新建成功",
                    icon: "success",
                  });
                  solutionDetail.value = e;
                  getSolutionData();
                  getPlanList();
                });
              });
            });
          });
          wellModalRef.value.closeModal();
        });
      }
    }
  }
}

// 打开方案列表弹窗
function openList() {
  listModalRef.value.openModal();
}

// 选择解决方案
function solutionSelection(e) {
  console.log("solutionSelection", e);
  localStorage.setItem("solutionId", e.id); //存储解决方案ID
  localStorage.setItem("salvageWellId", e.wellId);
  // localStorage.setItem("isSalPoint", res.skew)
  querySurvey.value.wellId = e.wellId;
  WellSurvey.queryList(querySurvey.value).then((response) => {
    console.log("getSurveyData", response);
    localStorage.setItem("salvageFileId", response.content[0].id);
    localStorage.setItem("isSalPoint", response.content[0].skew)
  });
  getSolutionData();
  listModalRef.value.closeModal();
}

// 方案信息展示
function getSolutionData() {
  let solutionId = localStorage.getItem("solutionId");
  if (solutionId === undefined) {
    // 展示空信息
    console.log("空");
    collapse.value = "disabled";
    return false; // 在这里返回
  }
  // 如果 e 不是 undefined，则执行以下操作
  SalvageSchemes.getDataOne(solutionId).then((res) => {
    // 在这里处理获取到的数据
    console.log("解决方案信息", res);
    isDataReady.value = true
    solutionDetail.value = res;
    collapse.value = "header";
  });
}
getSolutionData();
// 获取所有方案
function getPlanList() {
  let query = { pageNum: 1, pageSize: 10, sortBy: "id", searchKey: "" };
  SalvageSchemes.queryList(query).then((response) => {
    allPlan.value = response.content;
  });
}
getPlanList();
// 返回
function returned() {
  selectAccident.value = false;
  selectCard.value = false;
}

// 生成报告
function exReport() {
  const query = { schemeId: fileIds.value.id, templateFileId: "" };
  const queryTemplate = { templateDesc: fileIds.value.type, templateVersion: "" };
  exportList(queryTemplate).then((r) => {
    // console.log('导出',r);
    query.templateFileId = r[r.length - 1].templateFileId;
    window.open(
      `/dev-api/salvage/threadcard/schemes/export?schemeId=${query.schemeId}&templateFileId=${query.templateFileId}`
    );
  });
}
</script>
